/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reyes.mysite.helper;

import java.util.List;
import reyes.mysite.dao.GenericDAO;
import reyes.mysite.jdo.Category;
import org.json.JSONObject;
import org.json.JSONArray;

/**
 *
 * @author reyesyang
 */
public class MethodHelper {
    public JSONObject getAllCategoriesJSON() {

        GenericDAO<Category> categoryDAO = new GenericDAO<Category>();
        String queryAllCategories = "select from " + Category.class.getName() + " order by name";
        List<Category> allCategories = null;
        JSONObject json = new JSONObject();
        JSONArray jsonCategories = new JSONArray();

        try {
            json.put("categories", jsonCategories);
            allCategories = categoryDAO.query(queryAllCategories);
            int categoriesCount = allCategories.size();
            int index = 0;

            while (categoriesCount > index) {
                Category tempCategory = allCategories.get(index);
                String name = tempCategory.getName();
                String nickName = tempCategory.getNickName();
                JSONObject jsonCategory = new JSONObject();

                jsonCategory.put("name", name);
                jsonCategory.put("nickName", nickName);
                jsonCategories.put(jsonCategory);

                index++;
            }
        } catch (Exception e) {
            System.out.println("Can't create category: Details: " + e.getMessage());
        } finally {
            categoryDAO.closePM();
            return json;
        }
    }
}
